package com.ycg.store.handler;

import com.ycg.store.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author YCG
 * @date 2024-05-02 21:03
 * @description 全局异常处理器
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(RuntimeException.class)
    public Result<String> handler(RuntimeException ex) {
        String errMsg = ex.getMessage();
        ex.printStackTrace();
        log.error("全局异常捕获.."+ ex.getMessage());
        return Result.error(errMsg);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<String> handler(MethodArgumentNotValidException ex) {
        StringBuilder errMsg = new StringBuilder();
        for (ObjectError allError : ex.getAllErrors()) {
            errMsg.append("&").append(allError.getDefaultMessage());
        }
        return Result.error(errMsg.delete(0,1).toString());
    }
}
